package com.joe.utils;

import com.joe.utils.db.ConnectionFactory;
import com.sun.rowset.CachedRowSetImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by joe on 2018/11/25
 */
public class DBUtils {
    private static final Logger logger = LoggerFactory.getLogger(DBUtils.class);

    public static boolean insert(String preSql, Object[] args) {
        try (
                Connection connection = ConnectionFactory.getConnection();
                PreparedStatement statement = makeStatement(connection, preSql, args)
        ) {
            return statement.executeUpdate() > 0;
        } catch (SQLException e) {
            logger.error("Error while execute insert! sql -> " + preSql, e);
        }
        return false;
    }

    public static boolean delete(String preSql, Object[] args) {
        try (
                Connection connection = ConnectionFactory.getConnection();
                PreparedStatement statement = makeStatement(connection, preSql, args)
        ) {
            return statement.executeUpdate() > 0;
        } catch (SQLException e) {
            logger.error("Error while execute delete! sql -> " + preSql, e);
        }
        return true;
    }

    public static boolean drop(String preSql, Object[] args) {
        return false;
    }

    public static int update(String preSql, Object[] args) {
        try (
                Connection connection = ConnectionFactory.getConnection();
                PreparedStatement statement = makeStatement(connection, preSql, args)
        ) {
            return statement.executeUpdate();
        } catch (SQLException e) {
            logger.error("Error while execute update! sql -> " + preSql, e);
        }
        return -1;
    }

    public static int alert(String preSql, Object[] args) {
        return -1;
    }

    public static ResultSet select(String sql, Object[] args) {
        CachedRowSetImpl cachedRowSet = null;
        try (
                Connection connection = ConnectionFactory.getConnection();
                PreparedStatement statement = makeStatement(connection, sql, args);
                ResultSet resultSet = statement.executeQuery()
        ) {
            cachedRowSet = new CachedRowSetImpl();
            cachedRowSet.populate(resultSet);
        } catch (SQLException e) {
            logger.error("Error while execute query! sql ->" + sql, e);
        }
        return cachedRowSet;
    }

    /**
     * 构建 prepareStatement
     */
    private static PreparedStatement makeStatement(Connection connection, String sql, Object[] args) throws SQLException {
        PreparedStatement statement = connection.prepareStatement(sql);
        for (int i = 0; i < args.length; i++) {
            statement.setObject(i + 1, args[i]);
        }
        return statement;
    }
}
